<?php
namespace app\api\controller;
use app\api\model\HousingResources;
use app\api\model\ElecOrder;
use app\api\model\Room;
use app\api\model\Tenant;
use app\api\model\Tenergy;
use think\Db;

class TimingTask extends Common
{
    //定时更新房间电表电量
    public function getTEnergy(){
        $tenantList = Tenant::getList('tt.tenant_id,tt.house_id,tt.room_id,tr.r_id,tr.elec_meter');
        foreach ($tenantList as $k => $v){
            $energy = [];
            if($v['elec_meter']){
                $data = $this->getProperty($v['elec_meter']);
                $ren = json_decode($data,true);
                foreach ($ren['data'] as $key => $value){
                    if($value['attribute'] == 'TEnergy'){
                        $energy['TEnergy'] = $value['value'];
                        $energy['h_id'] = $v['house_id'];
                        $energy['r_id'] = $v['room_id'];
                        $energy['name'] = $v['elec_meter'];
                        $energy['recording_time'] = date('Ymd', time()-86400) ;
                        $energy['create_time'] = time();
                        $energy['type'] = '2';

                        $order = [];
                        $order['h_id'] = $v['house_id'];
                        $order['r_id'] = $v['room_id'];
                        $order['recording_time'] = date('Ymd',time());
                        $order['order_id'] = date('YmdHis',time()).mt_rand(11111,99999);
                        $order['create_time'] = time();
                        $order['status'] = 1;
                        $order['t_id'] = $v['tenant_id'];
                        $param = [
                            'h_id' => $v['house_id'],
                            'r_id' => $v['room_id'],
                        ];
                        $new_TEnergy = $value['value'];
                        $res = Tenergy::addInfo($param,$energy,$new_TEnergy,$order);
                        ////日志
                        $logContent = "\r\n";
                        $logContent .= "Datetime: " . date("Ymd H:i:s") . ' time: ' . time() . "\r\n";
                        $logContent .= "energy: " . json_encode($energy) . "\r\n";
                        $logContent .= "order: " . json_encode($order) . "\r\n";
                        $logContent .= "Res: " . $res . "\r\n";
                        $this->writeLog($logContent, "getTEnergy");
                    }
                }
            }
        }
    }
    public function getPublicTEnergy(){
        $houseList = Tenant::getHouseId();
        foreach ($houseList as $k => $v){
            $roomInfo = Room::getPublicRoom($v['house_id']);
            $data = $this->getProperty($roomInfo['elec_meter']);
            $ren = json_decode($data,true);
            if($ren['code'] != 200){
                continue;
            }
            foreach ($ren['data'] as $key => $value){
                if($value['attribute'] == 'TEnergy'){
                    $energy['TEnergy'] = $value['value'];
                    $energy['h_id'] = $v['house_id'];
                    $energy['r_id'] = $roomInfo['r_id'];
                    $energy['name'] = $roomInfo['elec_meter'];
                    $energy['recording_time'] = date('Ymd', time());
                    $energy['create_time'] = time();
                    $energy['type'] = '1';
                    $where = [
                        'h_id' => $v['house_id'],
                        'r_id' => $roomInfo['r_id'],
                    ];
                    $lastInfo = Tenergy::getLastInfo($where);
                    $energy['change'] = $value['value'] - $lastInfo['TEnergy'];
                    $res = Tenergy::addInfoOnly($energy);
                    $where1 = ['hr_id' => $v['house_id']];
                    $res3 = HousingResources::updateStatistics($where1,$energy['change']);
                    $update['public_usage'] = $energy['change'];
                    $where2 = [
                        'h_id' => $v['house_id'],
                        'recording_time' => date('Ymd',time()),
                    ];
                    ElecOrder::updateOrder($where2,$update);
                }
            }
        }
    }
    public function calculateOrder(){
        Db::startTrans();
        try{
            $houseList = Tenant::getHouseId();
            foreach ($houseList as $k => $v){
                $where = ['house_id' => $v['house_id'],'tenant_status' => 1];
                $num = Tenant::getNum($where);
                $update['checkin_num'] = $num;
                $where2 =['h_id' => $v['house_id'],'recording_time' => date('Ymd',time())];
                ElecOrder::updateOrder($where2,$update);
            }
            $where1 =['recording_time' => date('Ymd',time())];
            $orderList = ElecOrder::getTadayList($where1);
            foreach ($orderList as $key => $value){
                $public_usage = $value['public_usage'];
                $room_usage = $value['room_usage'];
                $unit_price = $value['unit_price'];
                $checkin_num = $value['checkin_num'];
                $total = ($public_usage/$checkin_num + $room_usage) * $unit_price * 100;
                $where3 = ['o_id' => $value['o_id']];
                $save['total'] = ceil($total);
                $save['status'] = 2;
                    $info = Db::name('tenant')->where(['tenant_id' => $value['t_id']])->find();
                    $tenant_balance = $info['tenant_balance'] - ceil($total);
                    if($tenant_balance < 0){
                        $charge['tenant_balance'] = floor($tenant_balance);
                    }else{
                        $charge['tenant_balance'] = ceil($tenant_balance);
                    }

                    $res1 = Db::name('tenant')->where(['tenant_id' => $value['t_id']])->update($charge);
                    $res2 = ElecOrder::updateOrder($where3,$save);
                    if($res1 && $res2){
                        Db::commit();
                    }else{
                        Db::rollback();
                    }
            }
        }catch (\Exception $e){
            Db::rollback();
            return json($e->getMessage());
        }
    }
    //获取电表详情
    public function getProperty($name)
    {
        $url = 'http://49.235.160.151:8082/getProperty?device=' . $name;
        $data = $this->curlData($url, '', 'GET');
        return $data;
    }
}